const resultService = require('../services/resultService');

const resultController = {
  // 创建新的测评结果
    async createResult(ctx) {
      try {
        const resultData = ctx.request.body;
        
        // 确保resultData中包含user_id
        if (!resultData.user_id) {
          // 如果前端没有提供用户ID，从会话中获取
          const userId = ctx.state?.user?.id;
          if (!userId) {
            ctx.status = 401;
            ctx.body = {
              message: '未提供用户ID'
            };
            return;
          }
          resultData.user_id = userId;
        }
        
        const resultId = await resultService.createResult(resultData);
      
      ctx.status = 201;
      ctx.body = {
        message: '测评结果创建成功',
        resultId: resultId
      };
    } catch (error) {
      ctx.throw(400, error.message);
    }
  },
  
  // 查看个人所有测评记录
  async getUserResults(ctx) {
    try {
      const userId = ctx.state.user.id;
      
      const results = await resultService.getUserResults(userId);
      
      ctx.status = 200;
      ctx.body = results;
    } catch (error) {
      ctx.throw(500, error.message);
    }
  },

  // 查看单个测评记录详情
  async getResultById(ctx) {
    try {
      const { id } = ctx.params;
      
      const result = await resultService.getResultById(id);
      
      ctx.status = 200;
      ctx.body = result;
    } catch (error) {
      ctx.throw(404, error.message);
    }
  },

  // 删除测评记录
  async deleteResult(ctx) {
    try {
      const userId = ctx.state.user.id;
      const { id } = ctx.params;
      
      // 检查结果是否属于当前用户
      const result = await resultService.getResultById(id);
      if (result.user_id !== userId) {
        ctx.throw(403, "无权限删除该测评结果");
      }
      
      await resultService.deleteResult(id);
      
      ctx.status = 200;
      ctx.body = { message: "测评记录删除成功" };
    } catch (error) {
      ctx.throw(404, error.message);
    }
  }
};

module.exports = resultController;